package com.enzoism.springboot.dive.chapter02;

import java.util.concurrent.*;

/**
 * @author Heian
 * @time 19/03/23 22:27
 * 用途：模拟异步发送接口
 * @link https://blog.csdn.net/qq_40826106/article/details/88628536
 */
public class Icallable {


    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        sendEmail sendEmail = new sendEmail(5000);
        sendPhoneMsg sendPhoneMsg = new sendPhoneMsg(8000);

        FutureTask<String> sendEmailTask = new FutureTask<>(sendEmail);
        FutureTask<String> sendPhonneMsgTask = new FutureTask<>(sendPhoneMsg);

        ExecutorService executorService = Executors.newFixedThreadPool(3);//线程池中的线程数目是固定的，来了多少任务，启动多少线程
        executorService.execute(sendEmailTask);
        executorService.execute(sendPhonneMsgTask);
        while (true) {
            if (!sendEmailTask.isDone()) {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println("emails发送中，请稍后" + Thread.currentThread().getName());
            }
            if (!sendPhonneMsgTask.isDone()) {
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println("短信发送中，请稍后" + Thread.currentThread().getName());
            }
            if (sendEmailTask.isDone() && sendPhonneMsgTask.isDone()) {
                System.out.println("两个线程执行完毕");
                executorService.shutdown();//所有线程执行完毕后再关闭
                return;
            }
            //执行完成
            long end = System.currentTimeMillis();
            System.out.println("耗时" + (end - start) + "毫秒");
        }
    }

    //Callable泛型为其异步返回的结果类型  Callable函数式接口
    static class sendEmail implements Callable<String> {
        private long sleepTime;

        public sendEmail(long sleepTime) {
            this.sleepTime = sleepTime;
        }

        @Override
        public String call() throws Exception {
            Thread.sleep(sleepTime);
            System.out.println("发送emails完毕：" + Thread.currentThread().getName());
            return Thread.currentThread().getName();
        }
    }

    static class sendPhoneMsg implements Callable<String> {
        private long sleepTime;

        public sendPhoneMsg(long sleepTime) {
            this.sleepTime = sleepTime;
        }

        @Override
        public String call() throws Exception {
            Thread.sleep(sleepTime);
            System.out.println("发送短信完毕：" + Thread.currentThread().getName());
            return Thread.currentThread().getName();
        }
    }


}